package com.yonyou.jrmob.lryapp.login;

import android.app.Activity;
import android.app.Dialog;
import android.app.admin.DevicePolicyManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.RequiresApi;
import android.support.design.widget.FloatingActionButton;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hss01248.dialog.StyledDialog;
import com.hss01248.dialog.config.ConfigBean;
import com.hss01248.dialog.interfaces.MyDialogListener;
import com.umeng.message.PushAgent;
import com.umeng.message.UTrack;
import com.yonyou.jr.mob.rzkh.R;
import com.yonyou.jrmob.application.bean.HomeMessageBean;
import com.yonyou.jrmob.lryapp.MainActivity;
import com.yonyou.jrmob.lryapp.view.LoginInput;
import com.yonyou.jrmob.lryapp.vo.AppAuth;
import com.yonyou.uap.emm.http.HttpCallback;
import com.yonyou.uap.emm.service.IUAPEMMService;
import com.yonyou.uap.emm.util.EmmUtil;
import com.yonyou.uap.emm.util.EnterpriseMobileManager;
import com.yonyou.uap.emm.util.deviceAdminReceiver;
import com.yonyou.uap.um.service.ServiceCallback;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import jrmob.yonyou.com.commonlib.app_config_tool.constant.Constant;
import jrmob.yonyou.com.commonlib.app_config_tool.gkh.MAServices_gkh;
import jrmob.yonyou.com.commonlib.app_config_tool.tool.base.CommonUtil;
import jrmob.yonyou.com.commonlib.app_config_tool.tool.base.LogUtils;
import jrmob.yonyou.com.commonlib.app_config_tool.tool.base.StatusBarUtil;
import jrmob.yonyou.com.commonlib.baseui.base.BaseActivityMob_lib;
import jrmob.yonyou.com.commonlib.baseui.base.BaseApp_lib;
import jrmob.yonyou.com.commonlib.login.bean.LoginBean;
import jrmob.yonyou.com.commonlib.login.bean.UserInfoLRY;

public class LoginActivity extends BaseActivityMob_lib {
    @BindView(R.id.login_progress)
    ProgressBar loginProgress;
    @BindView(R.id.login_logo_yg)
    ImageView loginLogo;
    @BindView(R.id.login_name)
    LoginInput loginName;
    @BindView(R.id.login_password)
    LoginInput loginPassword;
    @BindView(R.id.login_button)
    Button loginButton;
    @BindView(R.id.login_test)
    FloatingActionButton loginTest;
    private Dialog loadingDialog;
    InputMethodManager manager;
    private String oldUserName = "";
    private String newUserName = "";

    private UserInfoLRY userInfoLRY;
    private String toObject;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);
        initData();
        initLoginInput();
    }


    @Override
    protected void onResume() {
        super.onResume();
        StatusBarUtil.setStatusBarColor(this,R.color.login_titlebar);
        setDefaultNamePw();

    }

    /**
     * 设置默认账号和密码
     */
    public void setDefaultNamePw() {
        loginName.getContent().setText(readLocationValue(Constant.LOGIN_USER_NAME));
        loginPassword.getContent().setText(readLocationValue(Constant.LOGIN_USER_PWD));
    }


    @Override
    public boolean onTouchEvent(MotionEvent event) {
        manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            if (getCurrentFocus() != null && getCurrentFocus().getWindowToken() != null) {
                manager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
        return super.onTouchEvent(event);
    }

    @RequiresApi(api = Build.VERSION_CODES.CUPCAKE)
    private void initLoginInput() {
        loginName.setType(LoginInput.INPUT_TYPE.NAME);
        loginPassword.setType(LoginInput.INPUT_TYPE.PASSWORD);
//        loginName.getContent().setText("jun1");
//        loginPassword.getContent().setText("imfbp1");
        loginPassword.getContent().setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                /*判断是否是“GO”键*/
                if (actionId == EditorInfo.IME_ACTION_GO) {
                    /*隐藏软键盘*/
                    InputMethodManager imm = (InputMethodManager) v
                            .getContext().getSystemService(
                                    Context.INPUT_METHOD_SERVICE);
                    if (imm.isActive()) {
                        imm.hideSoftInputFromWindow(
                                v.getApplicationWindowToken(), 0);
                    }
                    callService();
                    return true;
                }
                return false;
            }
        });
    }

    @Override
    public void initView() {

    }

    @Override
    public void initListener() {

    }

    @Override
    public void initData() {
        //        默认ip
        String local_ip = readLocationValue(Constant.MA_IP);
        String local_port = readLocationValue(Constant.MA_PORT);
        if (TextUtils.isEmpty(local_ip) && TextUtils.isEmpty(local_port)){
            writeLocationFile(Constant.MA_IP, Constant.ma_ip);
            writeLocationFile(Constant.MA_PORT, Constant.ma_port);
        }

        oldUserName = readLocationValue(Constant.LOGIN_USER_NAME);
        PushAgent mPushAgent = PushAgent.getInstance(this);
        mPushAgent.removeAlias(oldUserName, "yonyou", new UTrack.ICallBack() {
            @Override
            public void onMessage(boolean isSuccess, String message) {

            }
        });

    }

    @OnClick({R.id.login_button, R.id.login_test})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.login_button:
                callService();
                break;
            case R.id.login_test:
                final String local_ip = readLocationValue(Constant.MA_IP);
                String ip = TextUtils.isEmpty(local_ip) ? Constant.ma_ip : local_ip;
                final String local_port = readLocationValue(Constant.MA_PORT);
                String port = TextUtils.isEmpty(local_port) ? Constant.ma_port : local_port;

                ConfigBean bean = StyledDialog.buildNormalInput("配置IP", ip, port, "确定", "取消", new MyDialogListener() {
                    @Override
                    public void onFirst() {
                    }

                    @Override
                    public void onSecond() {
                    }

                    @Override
                    public void onGetInput(CharSequence input1, CharSequence input2) {
                        super.onGetInput(input1, input2);
                        writeLocationFile(Constant.MA_IP, TextUtils.isEmpty(input1 + "") ? local_ip : input1 + "");
                        writeLocationFile(Constant.MA_PORT, TextUtils.isEmpty(input2 + "") ? local_port : input2 + "");
                        BaseApp_lib.setIp_gkh(input1 + "");
                        BaseApp_lib.setPort_gkh(input2 + "");
                    }
                });
                bean.seInputColor(R.color.lry_theme);
                bean.setTitleColor(R.color.lry_theme);
                bean.setBtnColor(R.color.lry_theme, R.color.lry_theme, R.color.lry_theme);
                bean.setListItemColor(R.color.lry_theme, null);
                bean.show();

                break;
        }
//        startActivity(new Intent(LoginActivity.this, MainActivity.class));
//        finish();
    }

    String name;
    String pw;

    private void callService() {
        try {
            JSONObject json = new JSONObject();
            name = loginName.getContent().getText().toString();
            pw = loginPassword.getContent().getText().toString();
            writeLocationFile(Constant.LOGIN_USER_NAME, name);
            writeLocationFile(Constant.LOGIN_USER_PWD, pw);
            String ip = readLocationValue(Constant.MA_IP);
            String port = readLocationValue(Constant.MA_PORT);
            if (TextUtils.isEmpty(ip) || TextUtils.isEmpty(port)) {
                showToast("请设置IP端口");
                return;
            }
            BaseApp_lib.setIp_gkh(ip);
            BaseApp_lib.setPort_gkh(port);

            // 请求接口服务类型()
            json.put("transtype", Constant.user_auth);
            json.put("usercode", name);
            json.put("username", name);
            json.put("password", pw);
            // 请求服务方式
            json.put("requestMethod", "POST");
            json.put("reqmethod", "post");

            // 保存用户名
            writeLocationFile("usercode_rzzl",name);

            if (!CommonUtil.isNetworkConnected(this)) {
                CommonUtil.showToast(this, "当前网络不可用,请检查!");
                return;
            }
            loadingDialog = StyledDialog.buildLoading("登录中！").show();
            MAServices_gkh.callMACommonService(LoginActivity.this, new ServiceCallback() {
                @Override
                public void execute(JSONObject jsonObject) {

                    LogUtils.e("登录数据：" + jsonObject.toString());
                    try {
                        // 有错误的时候
                        if (jsonObject.opt("success") != null && !jsonObject.optBoolean("success")) {
                            StyledDialog.dismissLoading();
                            showMessage("登陆失败!");
                            return;
                        }

                        JSONObject userInfo = jsonObject.optJSONObject("loginInfo");
                        if (userInfo == null) {
                            StyledDialog.dismissLoading();
                            showMessage("登陆失败!");
                            return;
                        }
                        Constant.TOKEN = userInfo.optString("token");
                        userInfoLRY = new UserInfoLRY();
                        userInfoLRY.setTenant_id(userInfo.optString("tenantId") == null ? "" : userInfo.optString("tenantId"));
                        userInfoLRY.setCode(userInfo.optString("username") == null ? "" : userInfo.optString("username"));
                        userInfoLRY.setUser_code(userInfo.optString("username") == null ? "" : userInfo.optString("username"));
                        userInfoLRY.setUser_id(userInfo.optString("userId") == null ? "" : userInfo.optString("userId"));
                        userInfoLRY.setUser_name(userInfo.optString("username") == null ? "" : userInfo.optString("username"));
                        userInfoLRY.setToken(userInfo.optString("token") == null ? "" : userInfo.optString("token"));

                        toObject = jsonObject.toString();

                        //writeLocationObject(Constant.userInfoLry, userInfoLRY);
                        //saveDataToLocal(jsonObject);
                        //saveTaskListToLoccal(jsonObject);

                        // 登录 emm
                        //loginEmm();


                        //设置友盟
                        setAlisa();

                        Intent intent = new Intent();
                        intent.setClass(LoginActivity.this, MainActivity.class);
                        //新建bundle对象
                        Bundle bundle = new Bundle();
                        bundle.putSerializable("userInfoLRY",userInfoLRY);
                        intent.putExtra("toObject",toObject);
                        intent.putExtras(bundle);
                        StyledDialog.dismissLoading();
                        startActivity(intent);
                        finish();

                    } catch (Exception e1) {
                        LogUtils.e(e1);
                        e1.printStackTrace();
                        StyledDialog.dismissLoading();
                    }
                    LogUtils.e(jsonObject.toString());
                }

                @Override
                public void error(String s, String s1) {
                    StyledDialog.dismissLoading();
                    showMessage(s1);
                    LogUtils.e(s + " " + s1);
                }
            }, json);
        } catch (Exception e) {
            StyledDialog.dismissLoading();
            e.printStackTrace();
        }
    }

    /**
     * 保存首页task 列表
     * @param jsonObject 登录接口返回的结果
     */
    private void saveTaskListToLoccal(JSONObject jsonObject) {
        JSONArray jsonArray = jsonObject.optJSONArray("task_list");
        Gson gson = new Gson();
        ArrayList<HomeMessageBean> messageBeanList = gson.fromJson(jsonArray.toString(),  new TypeToken<ArrayList<HomeMessageBean>>() {}.getType());
        writeLocationObject(Constant.task_list, messageBeanList);
        EventBus.getDefault().post("finised");
    }

    /**
     * 保存小部件的对应的数值
     * @param jsonObject 登录接口返回的结果
     */
    private void saveDataToLocal(JSONObject jsonObject) {
        try {
            String customer_count = jsonObject.optString("customer_count");
            String payment_count = jsonObject.optString("payment_count");
            String contract_money = jsonObject.optString("contract_money");
            String task_count = jsonObject.optString("task_count");

            UserInfoLRY userInfoLRY = readLocationObject(Constant.userInfoLry, UserInfoLRY.class);
            userInfoLRY.setContract_money(contract_money);
            userInfoLRY.setPayment_count(payment_count);
            userInfoLRY.setCustomer_count(customer_count);
            userInfoLRY.setTask_count(task_count);
            writeLocationObject(Constant.userInfoLry, userInfoLRY);

            writeLocationFile(Constant.payment_count, payment_count);
            writeLocationFile(Constant.customer_count, customer_count);
            writeLocationFile(Constant.contract_money, contract_money);
            writeLocationFile(Constant.task_count, task_count);
            JSONArray jsonArray = jsonObject.optJSONArray("appAuth");
            int length = jsonArray.length();
            if (length == 0) {
                return;
            }
            Gson gson = new Gson();
            JSONObject jsonObject1;
            ArrayList<AppAuth> appAuths = new ArrayList<>();
            AppAuth appAuth;
            for (int i = 0; i < length; i++) {
                jsonObject1 = jsonArray.getJSONObject(i);
                appAuth = gson.fromJson(jsonObject1.toString(), AppAuth.class);
                appAuths.add(appAuth);
            }
            writeLocationObject(Constant.app_auth, appAuths);

        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    /*********** 登录 emm start *********/

    public static final String HTTP_emm = "http"; // emm 注册协议
    public static final int LOGIN_EMM_FAILED = 5980;  // 失败标识
    public static final int LOGIN_EMM_SUCCESS = 5880;  // 成功标识

    /**
     * 注册,登录emm
     */
    void loginEmm() {
        StyledDialog.updateLoadingMsg("努力加载中！");
        //showToast("登陆中...");
        Map map = BaseApp_lib.getMap_app();
        map.put("emm_ip", Constant.emmIP);
        map.put("emm_port", Constant.emmPORT);
        final String IP_emm =Constant.emmIP;
        final String PORT_emm = Constant.emmPORT;


        if (IP_emm.length() <= 7 || TextUtils.isEmpty(PORT_emm)) {
            showMessage("emm 配置有误,请检查!");
            StyledDialog.dismissLoading();
            return;
        }

        // emm 登录注册
        final EnterpriseMobileManager enterpriseMobileManager = new EnterpriseMobileManager(
                this, IP_emm, PORT_emm, HTTP_emm);
        new Thread(new Runnable() {
            @Override
            public void run() {
                regist(IP_emm, PORT_emm, Constant.emmUserName, Constant.emmPWD, null, enterpriseMobileManager);
            }
        }).start();


    }


    /**
     * handler
     */
    android.os.Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case LOGIN_EMM_FAILED:  // emm 报错
                    StyledDialog.dismissLoading();
                    showMessage(msg.obj);
                    break;
                case LOGIN_EMM_SUCCESS:  // emm 成功 (比如跳转到主界面)
                    setAlisa();
                    StyledDialog.dismissLoading();
                    intentToMainPageActivity();
                    break;
                default:
                    break;
            }
        }
    };

    private void setAlisa() {
        PushAgent mPushAgent = PushAgent.getInstance(this);
        newUserName = readLocationValue(Constant.LOGIN_USER_NAME);
        mPushAgent.removeAlias(oldUserName, "yonyou", new UTrack.ICallBack() {
            @Override
            public void onMessage(boolean isSuccess, String message) {

            }
        });

        mPushAgent.addAlias(newUserName, "yonyou", new UTrack.ICallBack() {
            @Override
            public void onMessage(boolean isSuccess, String message) {

            }
        });

    }

    /******************  emm deviceadmin start *******************************/

    boolean isOpenDevice = true;//设备管理器激活标示

    public void openAdmin(ComponentName mDeviceAdminSample, Activity activity, int requestCode) {
        DevicePolicyManager mDPM = (DevicePolicyManager) activity.getSystemService(Context.DEVICE_POLICY_SERVICE);
        boolean active = mDPM.isAdminActive(mDeviceAdminSample);
        if (!active) {
            if (isOpenDevice) {
                isOpenDevice = false;
                Intent intent = new Intent("android.app.action.ADD_DEVICE_ADMIN");
                intent.putExtra("android.app.extra.DEVICE_ADMIN", mDeviceAdminSample);
                intent.putExtra("android.app.extra.ADD_EXPLANATION", "说明: 此应用只针对移动工作台管控.");
                activity.startActivityForResult(intent, requestCode);
            } else {
                handler.sendEmptyMessage(LOGIN_EMM_SUCCESS);  //执行登陆
            }
        } else {
            handler.sendEmptyMessage(LOGIN_EMM_SUCCESS);  //执行登陆
        }

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 121) {
            handler.sendEmptyMessage(LOGIN_EMM_SUCCESS);  //执行登陆
        }

    }

    /**
     * emm 登录成功后调用
     *
     */
    public void openEmm(Context context, String host, String port, String emmusercode, String emmpwd) {
        EnterpriseMobileManager.startCommandServices(context, 5);
        ComponentName mDeviceComponentName = null;
        SharedPreferences sp = context.getSharedPreferences("UAPHomeConfigure", Context.MODE_PRIVATE);
        //MA
        sp.edit().putString("host", host).commit();
        sp.edit().putString("port", port).commit();

        //Emm
        sp.edit().putString(EmmUtil.EMMHOST, host).commit();
        sp.edit().putString(EmmUtil.EMMPORT, port).commit();


        sp.edit().putString("emmusercode", emmusercode).commit();
        sp.edit().putString("emmpwd", emmpwd).commit();


        EnterpriseMobileManager enterpriseMobileManager1 = new EnterpriseMobileManager(context, host, port);
        if (EmmUtil.isOpenEMM) {
            LogUtils.e("yyyBootReceiver - Emm is open");
            //EnterpriseMobileManager enterpriseMobileManager = new EnterpriseMobileManager(context,host , port);
            if (mDeviceComponentName == null)
                mDeviceComponentName = new ComponentName(context,
                        deviceAdminReceiver.class);

//            enterpriseMobileManager1.startStrategy(mDeviceComponentName, 2);
//            EnterpriseMobileManager.openAdmin();
            IUAPEMMService.url = EmmUtil.getEmmHost(context) + "/mobem/push/strategy";
            IUAPEMMService.mDeviceComponentName = mDeviceComponentName;
//            Intent Service = new Intent();
//            Service.setAction("android.intent.action.IUAPEMMService");
//            Service.setPackage(context.getPackageName());
            context.startService(new Intent(context, IUAPEMMService.class));

            // 是否强制性打开设备管理器
//            EnterpriseMobileManager.openAdmin(mDeviceComponentName, mActivity, 121);
            openAdmin(mDeviceComponentName, mActivity, 121);

            Intent startServiceIntent = new Intent();
            startServiceIntent.setAction("android.intent.action.IUAPWatchService");
            startServiceIntent.setPackage(context.getPackageName());
            context.startService(startServiceIntent);

            enterpriseMobileManager1.startGroupService(3);
        } else {
            LogUtils.e("yyyBootReceiver - Emm关闭");
            handler.sendEmptyMessage(LOGIN_EMM_SUCCESS);  //执行登陆
        }
    }


    /**********************  emm deviceadmin end  ***************************/


    private void intentToMainPageActivity() {
        Intent intent = new Intent();
        intent.setClass(LoginActivity.this, MainActivity.class);
        //新建bundle对象
        Bundle bundle = new Bundle();
        bundle.putSerializable("userInfoLRY",userInfoLRY);
        //bundle.putSerializable("toObject", (Serializable) toObject);
        intent.putExtra("name",name);
        intent.putExtra("pwd",pw);
        intent.putExtra("toObject",toObject);
        //bundle.putString("name",name);
        //bundle.putString("pwd",pw);
        intent.putExtras(bundle);
        startActivity(intent);
        finish();
    }

    //注册EMM
    private void regist(final String host, final String port, final String user, final String passwd,
                        final String enterpriseID, EnterpriseMobileManager enterpriseMobileManager) {
        try {
            enterpriseMobileManager.registerUser(user, passwd, enterpriseID,
                    new HttpCallback() {

                        @Override
                        public void execute(String arg0) {

                            //标记
                            if (TextUtils.isEmpty(arg0)) {
                                LogUtils.e("EMM登录有误! " + arg0);
                                Message message = new Message();
                                message.obj = arg0;
                                message.what = LOGIN_EMM_FAILED;
                                handler.sendMessage(message);
                                return;
                            }
                            try {
                                final JSONObject jsonObject = new JSONObject(arg0);
                                String code = jsonObject.getJSONObject("data").getString("code");
                                // 注册成功
                                if ("1".equals(code)) {
                                    Message message = new Message();
                                    message.what = LOGIN_EMM_SUCCESS;
                                    handler.sendMessage(message);

                                    //启动emm 监控service
//                                    openEmm(mActivity, host, port, user, passwd);

                                } else if ("0".equals(code)) {
                                    String status = jsonObject.getJSONObject("data").getString("status");
                                    String msg = jsonObject.getJSONObject("data").optString("msg", "");
                                    if (status.equals("0")) {

                                        if (mActivity != null) {
                                            LogUtils.e("EMM登录有误! " + arg0);
                                            Message message = new Message();
                                            message.obj = arg0;
                                            message.what = LOGIN_EMM_FAILED;
                                            handler.sendMessage(message);
                                        }

                                    } else if (status.equals("4")) {

                                        //android 7.0
                                        writeLocationFile(EmmUtil.EMMUSER, "");

                                        if (mActivity != null) {
                                            Message message = new Message();
                                            message.obj = arg0;
                                            message.what = LOGIN_EMM_FAILED;
                                            handler.sendMessage(message);
                                        }
                                    }
                                }
                            } catch (JSONException e) {
                                LogUtils.e(e);
                                e.printStackTrace();
                            }
                        }
                    });
        } catch (Exception e) {
            LogUtils.e(e);
            e.printStackTrace();
        }

    }


    /*********** 登录 emm end *********/


}

